package com.leostadyn.stackfarm.timestatistics.net.base;

import android.content.Intent;

import com.leostadyn.stackfarm.timestatistics.BuildConfig;
import com.leostadyn.stackfarm.timestatistics.base.BaseApplication;
import com.leostadyn.stackfarm.timestatistics.common.Constants;
import com.leostadyn.stackfarm.timestatistics.model.bean.BaseResponse;
import com.leostadyn.stackfarm.timestatistics.utils.SaveObjectTools;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

public abstract class OriginalSubscriber<T> implements Observer<BaseResponse<T>> {

    private CompositeDisposable compositeDisposable;
    private Disposable mDisposable;

    public OriginalSubscriber(CompositeDisposable compositeDisposable) {
        this.compositeDisposable = compositeDisposable;
        if (this.compositeDisposable == null) {// 防止为null，概览很低
            this.compositeDisposable = new CompositeDisposable();
        }
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        mDisposable = d;
        compositeDisposable.add(mDisposable);
    }

    @Override
    public void onNext(BaseResponse<T> rBaseResponse) {
        if ("success".equals(rBaseResponse.getCode())) {
            if (rBaseResponse.getData() == null) {
                onNext(null, rBaseResponse.getMessage());
            } else {
                onNext(rBaseResponse.getData(), rBaseResponse.getMessage());
            }
        } else if ("fail_auth_check".equals(rBaseResponse.getCode())) {
            //apptoken err
            onNext(null, rBaseResponse.getMessage());
        } else {
            onError(new ResponseThrowable(rBaseResponse.getCode(), rBaseResponse.getMessage()));
        }
    }

    @Override
    public void onError(Throwable e) {
        onError(ExceptionHandler.handleException(e));
        compositeDisposable.remove(mDisposable);
    }


    @Override
    public void onComplete() {
        compositeDisposable.remove(mDisposable);
        mDisposable.dispose();
        mDisposable = null;
    }


    public abstract void onError(ResponseThrowable e);

    public abstract void onNext(T t, String msg);

    public Disposable getmDisposable() {
        return mDisposable;
    }

    public void appTokenErr(String msg) {
        SaveObjectTools.INSTANCE().saveData(null, Constants.USERINFO);
        Intent intent = new Intent();
        intent.setAction(BuildConfig.APPLICATION_ID);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        BaseApplication.getApplication().startActivity(intent);
    }
}
